package middleware

import (
	"content_system/dao/redis"
	"content_system/value"
	"github.com/gin-gonic/gin"
	"net/http"
)

const (
	SessionID = "k_session_id"
	UserID    = "k_user_id"
)

type SessionAuth struct {
}

func NewSessionAuth() *SessionAuth {
	return &SessionAuth{}
}

func (s *SessionAuth) Auth(ctx *gin.Context) {
	sessionID := ctx.GetHeader(SessionID)
	if sessionID == "" {
		ctx.AbortWithStatusJSON(http.StatusForbidden, value.Forbidden())
		return
	}
	uid, err := redis.GetUserIDBySessionID(ctx, sessionID)
	if err != nil {
		ctx.AbortWithStatusJSON(http.StatusForbidden, value.Forbidden())
		return
	}
	ctx.Set(UserID, uid)
	ctx.Next()
}
